import traceback
from operator import itemgetter

from flask import render_template, current_app, session, request, jsonify

from info import constants, db
from info.models import User, News, Category
from info.modules.index import index_blue
from info.utils.response_code import RET


@index_blue.route('/')
def hello_world():
    # 获取session数据
    user_id = session.get("user_id")

    user = None
    # 判断数据是否存在
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    # 获取点击排行数据
    news_list = None
    # 查询数据库按点击量降序，只查询前10条
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
        # news_list = db.session.query(News).all()
    except Exception as e:
        traceback.print_exc(e)
        current_app.logger.error(e)

    click_news_list = []

    if news_list:
        # 将获取到的数据进行遍历排序
        for i in news_list:
            click_news_list.append(i.to_basic_dict())
        click_news_list = sorted(click_news_list, key=itemgetter("clicks"), reverse=True)

    # 显示排行
    categorys = None
    try:
        categorys = Category.query.all()
        categorys_list = []
        for category in categorys:
            categorys_list.append(category.to_dict())
        # print("categorys_list---->", categorys_list)
    except Exception as e:
        current_app.logger.error(e)

    # 新闻数据显示
    news_all = None
    try:
        news_all = News.query.all()
    except Exception as e:
        current_app.logger.error(e)


    data = {
        "user_info": user.to_dict() if user else None,
        "click_news_list": click_news_list,
        "categorys_list": categorys
    }
    return render_template("/news/index.html", data=data)


@index_blue.route("/favicon.ico")
def favicon():
    return current_app.send_static_file("news/favicon.ico")


@index_blue.route("/newslist")
def get_news_list():
    """
    获取指定分类的新闻列表
    1、获取参数
    2、校验参数
    3、查询数据
    4、返回数据
    :return:
    """
    # 1、获取参数
    args_dict = request.args
    page = args_dict.get("page", "1")  # 获取页数
    per_page = args_dict.get("per_page", constants.HOME_PAGE_MAX_NEWS)  # 每页数量
    category_id = args_dict.get("cid", '1')  # 分类id

    # 2、校验参数
    try:
        page = int(page)
        per_page = int(per_page)
        category_id = int(category_id)
        print("page=", page)
        print("per_page=", per_page)
        print("category_id=", category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3、查询数据并分页
    filters = []
    if category_id > 1:
        print("进入判断")
        filters.append(News.category_id == category_id)
    print(filters)
    try:
        pagination = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page=page,
                                                                                            per_page=per_page,
                                                                                            error_out=False)

        # 获取查询出来的数据
        news_list = pagination.items
        # # 获取到总页数
        total_page = pagination.pages
        # # 当前页对象
        current_page = pagination.page

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    news_li = []
    for news in news_list:
        news_li.append(news.to_basic_dict())

    # 4、返回数据
    return jsonify(errno=RET.OK, errmsg="ok", totalPage=total_page, currentPage=current_page, cid=category_id,
                   newsList=news_li)
